package com.yuanjun.product.controller.admin;


import com.alibaba.fastjson.JSONObject;

import com.yuanjun.product.entity.JczSysAdmin;
import com.yuanjun.product.service.AdminUserService;
import com.yuanjun.product.vo.base.BaseResult;
import com.yuanjun.product.vo.common.Const;
import com.yuanjun.product.vo.req.ReqLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping(value = "/userLogin")
public class AdminLoginController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${spring.profiles.active}")
    private String ENV;
    @Autowired
    private AdminUserService adminUserService;
    @PostMapping("/login")
    public BaseResult login(@RequestBody ReqLoginVo reqLoginVo){
        if (StringUtils.isBlank(reqLoginVo.getAccount())||StringUtils.isBlank(reqLoginVo.getPassword())) {
            return BaseResult.createFail(Const.HttpRespCode.DATA_LACK, "用户名或密码不能为空");
        }
        JczSysAdmin adminUser = adminUserService.getAdminUserByAccount(reqLoginVo.getAccount());
        if (adminUser==null){
            return BaseResult.createFail(Const.HttpRespCode.INCOMPATIBLE_CONDITION, "无此账户");
        }
        if (!reqLoginVo.getPassword().equals(adminUser.getPassword())){
            return BaseResult.createFail(Const.HttpRespCode.NOT_FOUND, "您输入的密码不正确，请重新输入");
        }

        String token = Const.ADMIN_PREFIX + "-" + UUID.randomUUID().toString() + "-" + System.currentTimeMillis();
        log.info("生成的token:{}", token);
        stringRedisTemplate.opsForValue().set(token, JSONObject.toJSONString(adminUser), 3600, TimeUnit.SECONDS);
        Map<String,String> map = new HashMap<>();
        map.put("token",token);
        map.put("userName",adminUser.getUserName());
        return BaseResult.createOk(map);
    }

}
